package com.tingyu.blog.web;


import com.tingyu.blog.po.Comment;
import com.tingyu.blog.po.User;
import com.tingyu.blog.service.BlogService;
import com.tingyu.blog.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

@Controller
public class CommentController {
    @Autowired
    private CommentService commentService;
    @Autowired
    private BlogService blogService;
    @Value("${comment.avatar}")
    private String avatar;

    //显示评论列表
    @GetMapping("/comments/{blogId}")
    public String comments(@PathVariable int blogId, Model model){
        model.addAttribute("comments",commentService.listCommentByBlogId(blogId));
        return "blog :: commentList";   //仅返回blog详情页中的评论片段
    }


    //post提交评论
    @PostMapping("comments")
    public String postComment(Comment comment, HttpSession session){
        int blogId = comment.getBlog().getId();     //获取博客id
        comment.setBlog(blogService.getBlog(blogId));   //设置评论关联博客
        User user = (User) session.getAttribute("user");
        if (user != null){
            comment.setAvatar(user.getAvatar());
            comment.setAdminComment(true);
        }else {
            comment.setAvatar(avatar);      //设置头像
        }
        commentService.saveComment(comment);    //保存评论
        return "redirect:/comments/" + blogId;      //重定向到显示评论列表连接
    }
}
